package com.newland.starpos.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.newland.starpos.persistent.entity.User;
import com.newland.starpos.project.dto.UserDTO;
import com.newland.starpos.project.exception.BadRequestException;
import com.newland.starpos.project.http.ResponseModel;
import com.newland.starpos.project.service.UserService;
import com.newland.starpos.project.utils.BeanUtils;
import com.newland.starpos.project.utils.StringUtils;

@RestController
@RequestMapping(value = "/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@PostMapping
	public ResponseModel<UserDTO> create(@RequestBody UserDTO dto) {
		User user = BeanUtils.transfrom(User.class, dto);
		Assert.notNull(user.getName(), "user name is not allowed null");
		if(!StringUtils.hasText(user.getName())) {
			throw new BadRequestException("user name is not allowed null");
		}
		User existUser = userService.findOne(user.getName());
		if(existUser != null) {
			throw new BadRequestException("name has been taken up");
		}
		user = userService.save(user);
		dto = BeanUtils.transfrom(UserDTO.class, user);
		return ResponseModel.ok(dto);
	}
	
}
